function createWebSocket(url) {
    //var url = 'ws://' + gateWayUrl + '/websocket/chat/' + currentUserId;
    var webSocket = new WebSocket(url);
    webSocket.onopen = webSocketConnect;
    webSocket.onclose = webSocketClose;
    webSocket.onmessage = webSocketReceiverMessage;
    webSocket.onerror = webSocketError;
    return webSocket;
}

function webSocketConnect() {
    console.log('webSocket连接创建。。。');
}

function webSocketClose() {
    webSocket = null;
    Ext.Msg.alert("异常", "服务器连接已断开,请尝试重新刷新页面");
    console.log('webSocket断开连接。。。');
}

//当收到消息时
function webSocketReceiverMessage(event) {
    var msg = JSON.parse(event.data);
    if (msg.type == 0) {//如果是聊天消息的话
        var senderPanel = chattingListPanel.queryById(msg.sender);
        taskTabPanel.setActiveTab(2);//确保收到消息时页面在聊天面板
        if (senderPanel == null) {//如果发送消息的那个人现在不在列表里
            senderPanel = Ext.create('chattingBase', msg.sender, msg.senderName);
            chattingListPanel.insert(0, senderPanel);//新建聊天框添加
        }
        senderPanel.add(Ext.create('leftChatMsgBox',//将消息添加到聊天框
            msg.id,
            msg.message));
        if (senderPanel.getCollapsed()) {//如果panel未展开就要将新消息以未读状态处理
            senderPanel.notReadMessages.push(msg);//保存未读消息
            senderPanel.setTitle(senderPanel.senderName + '(新消息:' + senderPanel.notReadMessages.length + '条)');
            updateChattingTabNoReadCount(++chattingTotalNoReadCount);//更新tab的未读数量显示
        } else {//如果panel展开就要将新消息以已读状态处理
            msg.type = 1;//消息类型
            webSocketSendMessage(webSocket, msg)//发送消息说这些消息都已经读了
            senderPanel.setScrollY(1000000);//将滚动条滑倒最低端
        }
        senderPanel.topMsgId = msg.id;//保存目前最顶端消息Id
    } else if (msg.type == 2) {//如果是历史消息的话
        var targetChattingId = msg.sender == currentUserId ? msg.receiver : msg.sender;//判断发往哪个聊天框
        var leftOrRight = msg.sender == currentUserId ? 1 : 0;//判断这个历史消息我是发送者还是接收者
        var targetChatting = chattingListPanel.queryById(targetChattingId);
        if (leftOrRight == 0)
            targetChatting.insert(0, Ext.create('leftChatMsgBox',//将消息添加到聊天框
                msg.id,
                msg.message));
        else
            targetChatting.insert(0, Ext.create('rightChatMsgBox',//将消息添加到聊天框
                msg.id,
                msg.message));
        targetChatting.topMsgId = msg.id;//保存目前最顶端消息Id
        targetChatting.setScrollY(0);//将滚动条滑倒最顶端
    } else if (msg.type == 3) {//如果是让他们注销登陆
        Ext.Msg.alert("异常", "该账户在其他地方登陆！");
        userLogout();
    }


}

//发送消息
function webSocketSendMessage(webSocket, message) {
    webSocket.send(JSON.stringify(message));
}

function webSocketError() {
    console.log('webSocket连接异常。。。');
}